import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';

class LoadNativeMediaImage extends StatefulWidget {
  const LoadNativeMediaImage({super.key});

  @override
  _LoadNativeMediaImageState createState() => _LoadNativeMediaImageState();
}

class _LoadNativeMediaImageState extends State<LoadNativeMediaImage> {
  XFile? _image;  // 用来保存选择的图片

  // 请求权限的方法
  Future<void> _requestPermission() async {
    final status = await Permission.photos.request();
    if (status.isGranted) {
      _pickImage();  // 权限被允许后，继续选择图片
    } else {
      // 权限被拒绝
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('权限被拒绝，无法访问相册')),
      );
    }
  }

  // 选择图片的方法
  Future<void> _pickImage() async {
    final ImagePicker picker = ImagePicker();
    // 从相册选择图片
    final XFile? pickedFile = await picker.pickImage(source: ImageSource.gallery);

    if (pickedFile != null) {
      setState(() {
        _image = pickedFile;  // 更新状态，显示图片
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Load Photo Album Image')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            // 如果有图片，则显示图片，否则显示提示文字
            _image == null
                ? const Text('请选择一张图片')
                : Image.file(File(_image!.path)),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _requestPermission,
              child: const Text('从相册选择图片'),
            ),
          ],
        ),
      ),
    );
  }
}